package it.giuseppefrattura.wwdefence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
//import org.andengine.entity.sprite.Sprite;
//import org.andengine.input.touch.TouchEvent;

import android.util.Log;

//import android.util.Log;

public class GameScene extends Scene{

	public Soldier ship;
	Camera mCamera;
	private int enemynumber,enemynumber1=0;
	float startX,startY=0;
	private char[][] v;
	public LinkedList<Bullets> bulletList;
	public int bulletCount;
	LinkedList<Enemy> E;
	int killed=0;
	ArrayList<Mattonella> matt;
	
	public GameScene() {
		//carica la mappa
		this.loadMap(1);
		E = new LinkedList<Enemy>();
		MainActivity.getSharedInstance().setCurrentScene(this);
	    setBackground(new Background(0.8f, 0.6f, 0.0f));
	    mCamera = MainActivity.getSharedInstance().mCamera;
		bulletList = new LinkedList<Bullets>();
		//crea gli enemy
		createSpriteSpawnTimeHandler(v);
		registerUpdateHandler(new GameLoopUpdateHandler());
	}
	
	public void cleaner() {
		synchronized (this) {
	        //In input l'iteratore d proiettili e nemici
			Iterator<Bullets> it = bulletList.iterator();
	        while (it.hasNext()) {
	            Bullets b = (Bullets) it.next();
	            if (b.sprite.getY() <= -b.sprite.getHeight()) {
	                BulletPool.sharedBulletPool().recyclePoolItem(b);
	                it.remove();
	                continue;
	            }
	            for (Enemy e : E) {
	            	if (e.getSprite().collidesWith(b.sprite)){
	            		e.colpito();
	            		if (e.dead() && e.getSprite().isVisible()) {
	            			//pulisci
	            			e.getSprite().setVisible(false);
	            			e.getSprite().detachSelf();
	            			e=null;
	            			E.remove(e);
	            			killed++;
	            			if (killed>enemynumber1-1){ //se li uccidi tutti
	            				//pulisci tutto!!!!
	            				enemynumber=-100;
	            				this.clearLevel();
	            				MainActivity.getSharedInstance().setCurrentScene(new WinScene());}
	            		}
	            	}
	            }
	        }
	        for (Enemy e : E) {
	        	if (e.getSprite().getX()>MainActivity.getSharedInstance().mCamera.getWidth()){
	        		if (e.getSprite().isVisible()){
	        		//La vita del giocatore diminuisce di uno
		        	//se arriva a 0 allora {
	        		enemynumber=-100;//smetto di generre nemici
	        	    this.clearLevel();
	        		MainActivity.getSharedInstance().setCurrentScene( new LoseScene());}//}
	        	}
	        }
	    }
	}
	
	private void clearLevel(){
		Iterator<Mattonella> itr = matt.iterator();
	    while (itr.hasNext()) {
	       Mattonella m = itr.next();
	       m.stopFire();
	       this.detachChild(m.getSprite());
	       m=null;
	    }
	    itr=null;
	    matt=null;
	}

	private void printScene(char[][] v){
		matt = new ArrayList<Mattonella>();
		for (int i=0; i<8; i++){
	    	for (int k=0; k<8; k++){
	    		int x = 100*i;
	    		int y = 60 *k;
	    		if (v[k][i]=='N'){
	    			Mattonella m = new Mattonella();
	    			m.getSprite().setPosition(x , y);
	    			m.getSprite().setVisible(true);
	    			m.getSprite().detachSelf();
	    	        attachChild(m.getSprite());
	    	        this.registerTouchArea(m.getSprite());
	    	        matt.add(m);
	    		}
	    	}
		}
		this.setTouchAreaBindingOnActionDownEnabled(true);
	}
	
	
	private void loadMap(int index){
		//Parte di inizializzazione della mappa
		Mappe m = new Mappe();
		try{
			v=m.getMappa(index);
			printScene(v);
			enemynumber = m.getEnemynumber(index);
			enemynumber1=enemynumber;
			startX=m.getStartX();
			startY=m.getStartY(index);
		}
		catch(Exception e){
			Log.w("Errore", "E' stata generato un errore a causa di una mappa");
		} 
		
	}
	
	
	private Enemy createEn(char [][] v){
		Enemy e = new Enemy();
		e.sposta(v);
		E.add(e);
		this.attachChild(e.getSprite());
		return e;
	}
	
	public void createSpriteSpawnTimeHandler(final  char [][] v)
    {  
        final TimerHandler spriteTimerHandler = new TimerHandler(4,true,new ITimerCallback()
            {                      
                @Override
                public void onTimePassed(final TimerHandler pTimerHandler)
                {
                    	if (enemynumber>0){ 
                    		createEn(v);
                    		enemynumber--;
                    	}
                }
            });  
        MainActivity.getSharedInstance().getEngine().registerUpdateHandler(spriteTimerHandler);
    }	
}
